import Vue from 'vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App'
import router from './router'

import store from './store'

import {getLocalToken,getPayload} from './utils'
import {refreshToken} from './api'

Vue.config.productionTip = false;    // 取消生产提示

/* eslint-disable no-new */
Vue.use(ElementUI);

router.beforeEach(function (to,from,next) {
  document.title = to.meta.title;    // 修改title
  if(to.meta.requireAuth){    // 校验用户权限
    let token = getLocalToken();
    if(!token){
      document.title = '登录';
      return next({path: '/login',query:{to:to.path}})
    }else{
      let payload = getPayload(token);
      let nowUTC = Math.floor(Date.now() / 1000);    // 当前utc时间(秒)
      let exp = payload.exp;    // token过期时间
      if(nowUTC >= exp){
        localStorage.removeItem('token');
        document.title = '登录';
        return next({path: '/login',query:{to:to.path}})
      }else if(to.meta.requireAdmin){
        if(!payload.is_admin){
          document.title = '登录';
          return next({path: '/login',query:{to:to.path}})
        }
      }
    }
  }
  if(to.path !=='/login'){
    refreshToken();    // 认证通过后，刷新token
  }
  return next();    // 正常进入路由
});

// setInterval(function(){ console.log("Hello"); }, 3000);

new Vue({
  el: '#app',
  router,
  render: h => h(App),
  store
});
